package gw.com.android.ui.onlive;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.gwtsz.android.rxbus.RxBus;

import org.json.JSONException;
import org.json.JSONObject;

import gw.com.android.app.AppMain;
import gw.com.android.app.GTConfig;
import gw.com.android.model.ConfigType;
import gw.com.android.model.DataManager;
import gw.com.android.ui.LoginWebFragment;
import gw.com.android.ui.MainActivity;
import gw.com.android.ui.quote2.QuoteChartConfig;
import gw.com.jni.library.terminal.GTSConst;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import www.com.library.model.DataItemDetail;

/**
 * @author jett
 * @since 2018-03-13.
 */
public class JiepanFragment extends LoginWebFragment {

    private boolean isGreenRise;
    private HideTask hideTask;
    private CompositeDisposable cd;
    private Disposable quoteTickRegister;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        ViewGroup view = (ViewGroup) super.onCreateView(inflater, container, savedInstanceState);
//        mWebView.setOnInterceptTouchListener(new View.OnTouchListener() {
//            @Override
//            public boolean onTouch(View v, MotionEvent event) {
//                if (event.getAction() == MotionEvent.ACTION_DOWN) {
//                    if (hideTask != null) {
//                        AppMain.getApp().getHandler().removeCallbacks(hideTask);
//                    }
//                    showTitle();
//                    showHomeTab();
//                } else if (event.getAction() == MotionEvent.ACTION_UP) {
//                    startHideTask(3000);
//                }
//                return false;
//            }
//        });
        isGreenRise = GTConfig.instance().getPrefColorConfig().equals(GTConfig.COLOR_GREEN_RISE);
        loadQuote(3);
        return view;
    }

    /**
     * 加载直接间后，先主动把伦敦金、伦敦银的行情推送过去
     * <p>
     * 直播间可能加载缓慢，帮分多次推送吧！
     */
    private void loadQuote(int count) {
        if (count < 0) {
            return;
        }
        final int currCount = count - 1;
        AppMain.getApp().getHandler().postDelayed(new Runnable() {
            @Override
            public void run() {
                DataItemDetail model = DataManager.instance().getTickModel(QuoteChartConfig.LONDON_GOLD);
                if (model != null) {
                    updateLiveQuote(model);
                }
                model = DataManager.instance().getTickModel(QuoteChartConfig.LONDON_SILVER);
                if (model != null) {
                    updateLiveQuote(model);
                }
                loadQuote(currCount);
            }
        }, 2000);
    }

    /**
     * 更新直播间的行情报价，
     * 直播间仅需要 伦敦金、伦敦银
     */
    private void updateLiveQuote(DataItemDetail model) {
        int code = model.getInt(GTSConst.JSON_KEY_CODEID);
        String key;
        if (code == QuoteChartConfig.LONDON_GOLD) {
            key = "GOLD";
        } else if (code == QuoteChartConfig.LONDON_SILVER) {
            key = "SILVER";
        } else {
            return;
        }
        String name = DataManager.instance().getPrdName(model);
        String currPrice = model.getString(GTSConst.JSON_KEY_CURPRICE);
        String rise = model.getString(GTSConst.JSON_KEY_RISE);
        String percent = model.getString(GTSConst.JSON_KEY_PERCENT);
        percent = String.format("%s%%", percent);
        try {
            JSONObject param = new JSONObject();
            JSONObject json = new JSONObject();
            json.put("code", code);
            json.put("name", name);
            json.put("now", currPrice);
            json.put("fluctuate", rise);
            json.put("percent", percent);
            json.put("isGreenRise", isGreenRise);
            param.put(key, json);
            if (mWebView != null) {
                mWebView.loadUrl("javascript:toolJS.setViewPriceData('" + param.toString() + "')");
            }
        } catch (JSONException ignore) {
        }
    }

    private void registerTickUpdate() {
        if (quoteTickRegister == null) {
            quoteTickRegister = RxBus.getInstance().register(GTSConst.REPLY_SYMBOL_TICK_UPDATE + "", DataItemDetail.class).subscribe(new Consumer<DataItemDetail>() {
                @Override
                public void accept(@NonNull final DataItemDetail model) {
                    updateLiveQuote(model);
                }
            });
        }
        if (cd == null) {
            cd = new CompositeDisposable();
        }
        cd.add(quoteTickRegister);
    }

    private void unRegisterTickUpdate() {
        if (cd != null) {
            cd.clear();
        }
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        onVisibleChange();
    }

    @Override
    public void onResume() {
        super.onResume();
        onVisibleChange();
    }

    private void onVisibleChange() {
        if (canVisible()) {
//            startHideTask(3001);
            registerTickUpdate();
        } else {
            removeHideTask();
            unRegisterTickUpdate();
        }
    }

    private boolean canVisible() {
        Fragment parent = getParentFragment();
        return isResumed() && !isHidden() && isVisible() && parent != null && parent.isResumed() && !parent.isHidden();
    }

    private void startHideTask(long delay) {
        if (hideTask == null) {
            hideTask = new HideTask();
        }
        AppMain.getApp().getHandler().postDelayed(hideTask, delay);
    }

    private void removeHideTask() {
        if (hideTask != null) {
            AppMain.getApp().getHandler().removeCallbacks(hideTask);
        }
    }

    private class HideTask implements Runnable {
        @Override
        public void run() {
            MainActivity activity = (MainActivity) getActivity();
            if (canVisible() && activity != null && ConfigType.TAB_ONLIVE_TAG.equals(activity.mCurrentTag)) {
                hideTitle();
                hideHomeTab();
            }
        }
    }

    private void hideTitle() {
        Fragment parent = getParentFragment();
        if (parent != null) {
            ((MainLiveFragment) parent).hideTitleBar(500);
        }
    }

    private void hideHomeTab() {
        FragmentActivity activity = getActivity();
    }


}
